<?php
class ManageController extends Controller
{
	/**
	 * Declares class-based actions.
	 */
	public function actions()
	{
		return array(
			// They can be accessed via: index.php?r=site/page&view=FileName
			'page'=>array(
				'class'=>'CViewAction',
			),
		);
	}
	
	public function actionViewList()
	{
		if(isset($_GET['guid']))
		{
			$guid=$_GET['guid'];
			if(Item::model()->findByAttributes(array('guid'=>$guid))==null)
			{
				echo "invalid page";
				return;
			}
			$itemsDataProvider = new CActiveDataProvider('Item', array(
								'criteria'=>array(
										'condition'=>'guid=:guid',
										'params'=>array(':guid'=>$guid)
									),
								'pagination'=>array(
										'pageSize'=>20,
									),
								'sort'=>array(
										'defaultOrder'=>'version ASC',
									),
								)
							);
			$this->render('viewList', array('itemsDataProvider'=>$itemsDataProvider, 'guid'=>$guid));
		}
	}
	
	public function deleteDirectory($filePath)
	{
		if(count(scandir(dirname($filePath)))==2&&rmdir(dirname($filePath))==true)
			$this->deleteDirectory(dirname($filePath));
	}
	
	public function actionDeleteVersion()
	{
		if(Yii::app()->request->isAjaxRequest)
		{	
			$message='';
			if(isset($_POST['guid'])&&isset($_POST['version']))
			{
				$model=Item::model()->findByPk(array('guid'=>$_POST['guid'], 'version'=>$_POST['version']));
				if($model!=null&&$model->protected_by_hash==0)
				{
					$filePath=$model->file_path;
				
					$transaction=Yii::app()->db->beginTransaction();
					$result=$model->delete();
					if($result)
					{
						$res=unlink($filePath);
						if($res)
						{
							$message.='Version '.$_POST['version'].' is deleted';
							$this->deleteDirectory($filePath);
							$transaction->commit();
						}
						else
						{
							$message.='Failed on deleting the file on server.';
							$transaction->rollback();
						}
					}
					else
						$message.='Version '.$_POST['version'].' is not found';
					$rowsString=Item::model()->countByAttributes(array('guid'=>$_POST['guid']));
					$rows=(int)$rowsString;
					echo CJSON::encode(array($message, $rows));
				}
				else
				{
					$message.='This Version is protected by hash.';
					echo CJSON::encode(array($message, -1));
				}
			}
			else
			{
				$message.='Invalid parameters';
				echo CJSON::encode(array($message, -1));
			}
		}
	}
	
	public function actionDeleteVersionWithHash()
	{
		if(Yii::app()->request->isAjaxRequest)
		{
			$message='';
			if(isset($_POST['guid'])&&isset($_POST['hash']))
			{
				$model=Item::model()->findByAttributes(array('guid'=>$_POST['guid'], 'hash'=>$_POST['hash']));
				if($model!=null)
				{
					$filePath=$model->file_path;
				
					$transaction=Yii::app()->db->beginTransaction();
					$result=$model->delete();
					if($result)
					{
						$res=unlink($filePath);
						if($res)
						{
							$message.='The version with hash:'.$_POST['hash'].' is deleted';
							$this->deleteDirectory($filePath);
							$transaction->commit();
						}
						else
						{
							$message.='Failed on deleting the file on server.';
							$transaction->rollback();
						}
					}
					else
						$message.='The version with hash:'.$_POST['hash'].' is not found';
					$rowsString=Item::model()->countByAttributes(array('guid'=>$_POST['guid']));
					$rows=(int)$rowsString;
					echo CJSON::encode(array($message, $rows));
				}
				else
				{
					$message.='The hash you provide is not matched.';
					echo CJSON::encode(array($message, -1));
				}
			}
		}
	}
	
	public function actionAddVersion()
	{
		if(isset($_GET['guid']))
		{
			$guid=$_GET['guid'];
			$latestVersion=Item::model()->getLatestVersion($guid);
			if($latestVersion==null)
			{
				echo "Invalid URL";
			}
			else
			{
				$model=new Item;
				$model->scenario='create';
				
				$model->symbolic_name=$latestVersion->symbolic_name;
				$model->description=$latestVersion->description;
				if(isset($_POST['Item']))
				{
					date_default_timezone_set('America/New_York');
					$model->attributes=$_POST['Item'];
					$model->uploadedFile=CUploadedFile::getInstance($model,'uploadedFile');
					if($model->uploadedFile!=null)
					{
						$model->guid=$guid;
						$model->version=$latestVersion->version+1;
						$model->email_address=$latestVersion->email_address;
						$model->end_time=date("Y-m-d H:i:s");
						$model->hash=hash_file('md5', $model->uploadedFile->getTempName());
						$model->file_path='data'.DIRECTORY_SEPARATOR.$model->email_address.DIRECTORY_SEPARATOR.$model->guid.DIRECTORY_SEPARATOR.$model->version;
						$model->size=$model->uploadedFile->getSize();
						$model->object_type_ID=$latestVersion->object_type_ID;
						
						$transaction=Yii::app()->db->beginTransaction();
						if($model->save())
						{
							$result=$model->uploadedFile->saveAs($model->file_path);
							if($result)
							{
								$transaction->commit();
								$this->redirect("viewList?guid=".$guid);
							}
							else
							{
								$transaction->rollback();
            					echo $model->uploadedFile->getError();
							}
						}
						else
						{
		            		$transaction->rollback();
		            		print_r($model->getErrors());							
						}
					}
					
				}
				$this->render('addVersion', array('model'=>$model, 'latestVersion'=>$latestVersion));
			}
			
		}
		else
		{
			echo "Invalid URL";
		}
	}
	public function actionView()
	{
		if(isset($_GET['guid']))
		{
			if(isset($_GET['hash'])&&!isset($_GET['version']))
			{
				$model=Item::model()->with('objectType')->findByAttributes(array('hash'=>$_GET['hash'], 'guid'=>$_GET['guid']));
				if($model!=null)
				{
					$this->render("view", array('model'=>$model));
				}
				else
				{
					echo "Invalid Parameter";
				}
			}
			else if(isset($_GET['version'])&&!isset($_GET['hash']))
			{
				if($_GET['version']=='latest')
					$model=Item::model()->getLatestVersion($_GET['guid']);
				else
					$model=Item::model()->with('objectType')->findByAttributes(array('version'=>$_GET['version'], 'guid'=>$_GET['guid']));
				if($model!=null)
				{
					$this->render("view", array('model'=>$model));	
				}
				else
				{
					echo "Invalid Prameter";
				}
			}
			else
			{
				echo "Invalid URL";
			}
		}
		else
		{
			echo "Invalid URL";
		}
	}
	
	public function actionDownload()
	{
		if(isset($_GET['guid']))
		{
			if(isset($_GET['hash']))
			{
				$model=Item::model()->findByAttributes(array('guid'=>$_GET['guid'], 'hash'=>$_GET['hash']));
				if($model==null)
				{
					header('HTTP/1.1 404 Not Found');
				}
				else
				{
					header('Content-Description: File Transfer');
					header('Content-Type: application/octet-stream');
					header('Content-Disposition: attachment; filename='.basename($model->file_path));
					header('Content-Transfer-Encoding: binary');
					header('Expires: 0');
					header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
					header('Pragma: public');
					header('Content-Length: ' . $model->size);
					ob_clean();
					flush();
					readfile($model->file_path);
				}
			}
			else
			{
				$model=Item::model()->getLatestVersion($_GET['guid']);
				if($model==null)
				{
					header('HTTP/1.1 404 Not Found');
				}
				else
				{
					if($model->protected_by_hash)
					{
						header('HTTP/1.1 403 Forbidden');
					}
					else
					{
						header('Content-Description: File Transfer');
					    header('Content-Type: application/octet-stream');
					    header('Content-Disposition: attachment; filename='.basename($model->file_path));
					    header('Content-Transfer-Encoding: binary');
					    header('Expires: 0');
					    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
					    header('Pragma: public');
					    header('Content-Length: ' . $model->size);
					    ob_clean();
					    flush();
						readfile($model->file_path);
					}
				}
			}
		}
		else
		{
			header('HTTP/1.1 404 Not Found');
		}
			
	}
}
?>
